package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @Auther: wangrui
 * @Date: 2018/6/7 14:54
 * @Description:
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public ServerResponse<User> login(String username, String password) {


        int count = userMapper.checkUsername(username);
        if (count==0){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        //todo MD5加密
        String md5password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username, md5password);
        if (user == null){
            return ServerResponse.createByErrorMessage("密码不正确");
        }
        //将用户信息的密码zhikong置空
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功", user);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> register(User user) {
        ServerResponse<String> serverResponse = this.checkVaild(user.getUsername(), Const.USERNAME);
        if (!serverResponse.isSuccess()){
            return serverResponse;
        }
        ServerResponse<String> response = this.checkVaild(user.getEmail(), Const.EMAIL);
        if (!response.isSuccess()){
            return response;
        }
        /*int username = userMapper.checkUsername(user.getUsername());
        if (username > 0){
            return ServerResponse.createByErrorMessage("用户名已存在");
        }
        int email = userMapper.checkEmail(user.getEmail());
        if (email > 0){
            return ServerResponse.createByErrorMessage("Email已存在");
        }*/
        user.setRole(Const.Role.ROLE_CUSTOMER);
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int register = userMapper.insert(user);
        if (register == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");
    }

    /**
     * 验证用户名和邮箱是否已使用
     * @param str
     * @param type
     * @return
     */
    public ServerResponse<String> checkVaild(String str,String type){
        if (StringUtils.isNotBlank(type)){
            if (Const.USERNAME.equals(type)){
                int username = userMapper.checkUsername(str);
                if (username > 0){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if (Const.EMAIL.equals(type)){
                int email = userMapper.checkEmail(str);
                if (email > 0){
                    return ServerResponse.createByErrorMessage("邮箱已存在");
                }
            }
        }else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    /**
     * 根据用户名查询忘记密码的问题
     * @param username
     * @return
     */
    public ServerResponse<String> SelectQuestion(String username){
        ServerResponse<String> serverResponse = this.checkVaild(username, Const.CURRENT_USER);
        if (!serverResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String questionByUsername = userMapper.selectQuestionByUsername(username);
        if (StringUtils.isNotBlank(questionByUsername)){
            return ServerResponse.createBySuccess(questionByUsername);
        }
        return ServerResponse.createByErrorMessage("问题为空");
    }

    /**
     * 验证用户输入问题的答案是否正确，并将token放入缓存中
     * @param username
     * @param question
     * @param answer
     * @return
     */
    public ServerResponse<String> forgetCheckAnswer(String username,String question,String answer){
        int i = userMapper.checkAnswer(username, question, answer);
        if (i > 0){
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题答案错误");
    }


    /**
     * 忘记密码时修改密码提交--未登录状态
     * @param username
     * @param passwordNew
     * @param forgetToken
     * @return
     */
    public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
        ServerResponse<String> stringServerResponse = this.checkVaild(username, Const.USERNAME);
        if (stringServerResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        if (StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数有误，token没有获取到");
        }

        String forToken = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        if (StringUtils.isBlank(forToken)){
            return ServerResponse.createByErrorMessage("token已经失效");
        }
        if (StringUtils.equals(forgetToken,forToken)){
            String md5passwordnew = MD5Util.MD5EncodeUtf8(passwordNew);
            int i = userMapper.updatePasswordByUsername(username, md5passwordnew);
            if (i > 0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else {
            return ServerResponse.createByErrorMessage("token有误，请重新获取");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }

    public ServerResponse<String> resertPassword(String passwordOld,String passwordNew,User user){
        int checkPassword = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
        if (checkPassword == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i > 0){
            return ServerResponse.createBySuccess("密码修改成功");
        }
        return ServerResponse.createByErrorMessage("密码修改失败");
    }

    /**
     * 用户信息更新
     * @param user
     * @return
     */
    public ServerResponse<User> updateUserInfo(User user){
        int emailById = userMapper.checkUserEmailById(user.getEmail(), user.getId());
        if (emailById > 0){
            return ServerResponse.createByErrorMessage("邮箱已被使用");
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());

        int i = userMapper.updateByPrimaryKeySelective(updateUser);
        if (i > 0){
            return ServerResponse.createBySuccess("个人信息更新成功", updateUser);
        }
        return ServerResponse.createByErrorMessage("个人信息更新失败");
    }

    /**
     * 获取当前用户个人信息
     * @param id
     * @return
     */
    public ServerResponse<User> get_Information(Integer id){
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            return ServerResponse.createByErrorMessage("没有此用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }



    public ServerResponse checkAdminRole(User user){
        if (user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }


}
